/**
 * 
 */
package com.maohi.software.arii;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.maohi.software.arii.events.DependencyEvent;
import com.maohi.software.arii.events.DependencyListener;
import com.maohi.software.arii.jaxb2.Plugin;
import com.maohi.software.arii.jaxb2.Plugin.Dependencies.Dependency;
import com.maohi.software.arii.utils.Plugins;

/**
 * @author heifara
 * 
 */
public class DependencyHandler {
	private static Logger logger = Logger.getLogger(DependencyHandler.class.getName());

	@Inject
	private List<DependencyListener> dependencyListeners;

	public void addDependencyListener(DependencyListener aListener) {
		this.dependencyListeners.add(aListener);
		logger.debug(aListener);
	}

	public boolean checkDependencies(Map<String, Plugin> aPlugins) {
		for (Plugin iPlugin : aPlugins.values()) {
			if (!this.checkDependencyMissing(aPlugins, iPlugin)) {
				return false;
			}
		}
		return true;
	}

	public boolean checkDependencyMissing(Map<String, Plugin> aPlugins, Plugin aPlugin) {
		for (Dependency iDependency : aPlugin.getDependencies().getDependency()) {
			if (!aPlugins.containsKey(Plugins.getKey(iDependency))) {
				this.fireDependencyMissing(aPlugin, iDependency);
				return false;
			}
		}

		return true;
	}

	private void fireDependencyMissing(Plugin aPlugin, Dependency iDependency) {
		for (DependencyListener iListener : this.dependencyListeners) {
			iListener.dependencyMissing(new DependencyEvent(this, aPlugin, iDependency));
		}
	}

	public void removeDependencyListener(DependencyListener aListener) {
		this.dependencyListeners.remove(aListener);
		logger.debug(aListener);
	}

}
